/**
 * 代码实时注入
 * @param {string} code 注入的代码
 */
const sandboxProxies = new WeakMap()
export function codeInjection(code) {
	code = 'with (sandbox) {' + code + '}'
	const codeFunc = new Function('sandbox', code)
	return function (sandbox) {
		if (!sandboxProxies.has(sandbox)) {
			const sandboxProxy = new Proxy(sandbox, { has, get })
			sandboxProxies.set(sandbox, sandboxProxy)
		}
		return codeFunc(sandboxProxies.get(sandbox))
	}
	function has(target, key) {
		return true
	}
	function get(target, key) {
		if (key === Symbol.unscopables) return undefined
		return target[key]
	}
}
